import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from '@/router/routes'
import store from '@/store'
import {setTitle} from '@/lib/tools'

Vue.use(VueRouter)

// 取消路由跳转统一页面报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes, scrollBehavior: () => ({y: 0})
})

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
  
  // 设置页面标题
  to.meta.title && setTitle(to.meta.title)
  
  const isAuthenticated = store.getters['user/isLogin']
  if (to.name !== 'login' && !isAuthenticated) {
    next({name: 'login'})
  } else {
    next()
  }
  
})

export default router
